package edu.pw.p2pclient.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import edu.pw.p2pclient.R;
import edu.pw.p2pclient.data.DownloadAdapter;
import edu.pw.p2pclient.data.DownloadNode;
import edu.pw.p2pclient.logic.DownloadManager;

public class DownloadQueueFragment extends Fragment {

	public static final String TITLE = "Pobierane";

	private ListView mListView;
	private DownloadAdapter mAdapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.download_queue_fragment,
				container, false);

		mListView = (ListView) rootView.findViewById(R.id.downloadListView);
		mAdapter = DownloadManager.getInstance().getDownloadAdapter();
		DownloadManager.getInstance().getDownloadAdapter()
				.setParentActivity(getActivity());
		mListView.setAdapter(mAdapter);
		registerForContextMenu(mListView);
		setHasOptionsMenu(true);
		return rootView;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.fragment_download_queue, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.clearDownloadedItem:
			clearDownloaded();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		final DownloadNode node = mAdapter.getItem(info.position);
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setMessage(node.getFullPath())
				.setPositiveButton(
						node.getState() == DownloadNode.CANCELLED ? R.string.restart_download
								: R.string.cancel_download,
						new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								if (node.getState() == DownloadNode.CANCELLED)
									DownloadManager.getInstance()
											.scheduleDownload(node);
								else
									DownloadManager.getInstance()
											.cancelDownload(node);
							}
						});
		builder.show();
	}

	public void clearDownloaded() {
		mAdapter.clearDownloaded();
		DownloadManager.getInstance().saveDownloadingList();
	}
}
